

package com.jf.cloud.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.distribution.feign.DistributionFeignClient;
import com.jf.cloud.api.distribution.vo.DistributionSpuVO;
import com.jf.cloud.api.group.feign.GroupFeignClient;
import com.jf.cloud.api.seckill.feign.SeckillFeignClient;
import com.jf.cloud.api.seckill.vo.SeckillApiVO;
import com.jf.cloud.api.supplier.bo.SupplierDetailBO;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.i18n.LanguageEnum;
import com.jf.cloud.common.product.bo.*;
import com.jf.cloud.common.product.constant.CommissionSpuStatus;
import com.jf.cloud.common.product.constant.SpuType;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.product.constant.SupplierSpuType;
import com.jf.cloud.common.product.vo.*;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.product.mapper.SkuMapper;
import com.jf.cloud.product.mapper.SpuMapper;
import com.jf.cloud.product.model.SpuExtension;
import com.jf.cloud.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品es信息处理
 *
 * @author zz
 * @date 2020-10-28 15:27:24
 */
@Service
public class SpuEsSearchServiceImpl implements SpuEsSearchService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @Autowired
    private SpuCommService spuCommService;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @Autowired
    private BrandService brandService;
    @Autowired
    private GroupFeignClient groupFeignClient;
    @Autowired
    private SeckillFeignClient seckillFeignClient;
    @Autowired
    private DistributionFeignClient distributionFeignClient;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuStockService skuStockService;

    @Override
    public EsProductBO loadEsProductBO(Long spuId) {
        // 获取商品
        EsProductBO esProductBO = spuMapper.loadEsProductBO(spuId);
        //获取sku信息
        List<SkuVO> skuList = skuMapper.listSkuWithAttrBySpuId(esProductBO.getSpuId());
        Set<String> skuCode = new HashSet<>();
        for (SkuVO skuVO : skuList) {
            skuCode.add(skuVO.getPartyCode());
        }
        esProductBO.setPartyCodes(skuCode);
        //代销商品
        if (Objects.equals(esProductBO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value())){
            //如果是代销商品获取供应商名称
            ServerResponseEntity<SupplierDetailBO> supplier = supplierDetailFeignClient.getSupplierBySupplierId(esProductBO.getSupplierId());
            if (!Objects.isNull(supplier.getData())){
                //防止空指针异常
                esProductBO.setSupplierName(supplier.getData().getSupplierName());
            }
            //设置设置代销商品状态
            if (esProductBO.getSpuStatus() == 1){
                //1：上架 2: 部分上架
                //判断skuChoiceStatus是否 == 1：全选
                esProductBO.setCommissionSpuStatus(esProductBO.getSkuChoiceStatus() == 1? CommissionSpuStatus.PUT_SHELF.value():CommissionSpuStatus.PART_PUT_SHELF.value());
            }
            if (esProductBO.getSpuStatus() == 0){
                //3: 下架 4: 部分下架
                //判断skuChoiceStatus是否 == 1：全选
                esProductBO.setCommissionSpuStatus(esProductBO.getSkuChoiceStatus() == 1? CommissionSpuStatus.OFF_SHELF.value():CommissionSpuStatus.PART_OFF_SHELF.value());
            }
        }
        if (Objects.equals(esProductBO.getSpuStatus(), StatusEnum.ENABLE.value())) {
            esProductBO.setAppDisplay(Boolean.TRUE);
        } else {
            esProductBO.setAppDisplay(Boolean.FALSE);
        }
        // 获取分类、品牌、评论、库存、属性信息
        setEsProductInfo(esProductBO);
        // 团购活动商品，添加活动时间
        if (Objects.equals(esProductBO.getSpuType(), SpuType.GROUP.value())) {
            ServerResponseEntity<Date> responseEntity = groupFeignClient.getActivityStartTime(esProductBO.getActivityId());
            if (Objects.nonNull(responseEntity.getData())) {
                esProductBO.setActivityStartTime(responseEntity.getData().getTime());
            }
        }
        // 秒杀活动商品，添加活动时间,秒杀分类,并添加批次信息
        if (Objects.equals(esProductBO.getSpuType(), SpuType.SECKILL.value())) {
            ServerResponseEntity<SeckillApiVO> responseEntity = seckillFeignClient.getSeckillInfoById(esProductBO.getActivityId());
            SeckillApiVO seckillApiVO = responseEntity.getData();
            esProductBO.setActivityStartTime(seckillApiVO.getStartTime().getTime());
            esProductBO.setSelectedLot(seckillApiVO.getSelectedLot());
            esProductBO.setSeckillCategoryId(seckillApiVO.getCategoryId());
        }
        // 分销信息，添加是否属于分销商品，添加分销参数
        try {
            ServerResponseEntity<DistributionSpuVO> distributionRes = distributionFeignClient.getBySpuId(spuId);
            if (!distributionRes.isSuccess()) {
                esProductBO.setDistributionSpu(Boolean.FALSE);
                return esProductBO;
            }
            DistributionSpuVO distributionProdVO = distributionRes.getData();
            if (Objects.isNull(distributionProdVO)) {
                esProductBO.setDistributionSpu(Boolean.FALSE);
            } else {
                esProductBO.setDistributionSpu(Boolean.TRUE);
                EsDistributionInfoBO esDistributionInfoBO = new EsDistributionInfoBO();
                esDistributionInfoBO.setDistributionSpuId(distributionProdVO.getDistributionSpuId());
                esDistributionInfoBO.setAwardMode(distributionProdVO.getAwardMode());
                esDistributionInfoBO.setState(distributionProdVO.getState());
                esDistributionInfoBO.setParentAwardSet(distributionProdVO.getParentAwardSet());
                esDistributionInfoBO.setAwardNumbers(distributionProdVO.getAwardNumbers());
                esDistributionInfoBO.setParentAwardNumbers(distributionProdVO.getParentAwardNumbers());
                esProductBO.setDistributionInfo(esDistributionInfoBO);
            }
        } catch (Exception e) {
            return esProductBO;
        }
        return esProductBO;
    }


    /**
     * 获取分类、品牌、评论、库存、属性信息
     *
     * @param esProductBO 商品信息
     */
    private void setEsProductInfo(EsProductBO esProductBO) {
        // 获取sku信息
        List<SkuVO> skuList = skuService.listSkuWithAttrBySpuId(esProductBO.getSpuId());
        // 商品编码、商品条形码列表信息
        Set<String> partyCodes = new HashSet<>();
        Set<String> modelIds = new HashSet<>();
        for (SkuVO skuVO : skuList) {
            if (StrUtil.isNotBlank(skuVO.getPartyCode())) {
                partyCodes.add(skuVO.getPartyCode());
            }
            if (StrUtil.isNotBlank(skuVO.getModelId())) {
                modelIds.add(skuVO.getModelId());
            }
        }
        esProductBO.setPartyCodes(partyCodes);
        esProductBO.setModelIds(modelIds);
        // 获取品牌
        EsBrandBO brand = brandService.getEsBrandBO(esProductBO);
        esProductBO.setBrand(brand);
        if(!Objects.equals(esProductBO.getSpuType(), SpuType.SCORE.value())){
            // 获取平台分类数据
            CategoryVO category = categoryService.getInfo(esProductBO.getCategoryId());
            if (Objects.isNull(category)) {
                throw new LuckException("商品id:" + esProductBO.getSpuId() + "绑定的分类不存在");
            }
            esProductBO.setPrimaryCategoryId(category.getCategories().get(0).getCategoryId());
            esProductBO.setSecondaryCategoryId(category.getCategories().get(1).getCategoryId());
            // 平台三级分类信息
            esProductBO.setCategory(handleCategory(category));
            if (esProductBO.getAppDisplay() && !Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())) {
                esProductBO.setAppDisplay(Boolean.FALSE);
            }
            // 获取店铺分类数据
            if (Objects.nonNull(esProductBO.getShopCategoryId()) && !Objects.equals(esProductBO.getShopCategoryId(),-1L) && !Objects.equals(esProductBO.getShopCategoryId(), Constant.DEFAULT_ID)) {
                CategoryVO shopCategory = categoryService.getInfo(esProductBO.getShopCategoryId());
                if (Objects.isNull(shopCategory)) {
                    throw new LuckException("商品id:" + esProductBO.getSpuId() + "绑定的店铺分类不存在");
                }
                esProductBO.setShopPrimaryCategoryId(shopCategory.getCategories().get(0).getCategoryId());
                // 店铺二级分类信息
                esProductBO.setShopCategory(handleCategory(shopCategory));

                if (esProductBO.getAppDisplay() && !Objects.equals(shopCategory.getStatus(), StatusEnum.ENABLE.value())) {
                    esProductBO.setAppDisplay(Boolean.FALSE);
                }
            }
        }


        // 好评数量
        esProductBO.setGoodReviewNum(spuCommService.countGoodReview(esProductBO.getSpuId()));

        SpuExtension spuExtension = new SpuExtension();
        if (Objects.equals(esProductBO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())){
            spuExtension = spuExtensionService.getBySpuId(esProductBO.getSupplierSpuId());
        }else {
            spuExtension = spuExtensionService.getBySpuId(esProductBO.getSpuId());
        }

        // 商品库存
        Integer totalStock = skuStockService.getTotalBySpuId(spuExtension.getSpuId());
        if (Objects.isNull(totalStock)) {
            totalStock = spuExtension.getStock();
        }

        esProductBO.setStock(totalStock);
        esProductBO.setSaleNum(spuExtension.getSaleNum() + spuExtension.getWaterSoldNum());
        esProductBO.setActualSoldNum(spuExtension.getSaleNum());
        esProductBO.setWaterSoldNum(spuExtension.getWaterSoldNum());
        esProductBO.setCommentNum(spuExtension.getCommentNum());
        // 是否有库存
        esProductBO.setHasStock(Objects.nonNull(totalStock) && totalStock > 0);

        // 获取属性
        List<SpuAttrValueVO> spuAttrsBySpuId = spuAttrValueService.getSpuAttrsBySpuId(esProductBO.getSpuId());
        List<SpuAttrValueVO> attrs = spuAttrsBySpuId.stream().filter(spuAttrValueVO ->
                Objects.nonNull(spuAttrValueVO.getSearchType()) && Objects.equals(spuAttrValueVO.getSearchType(), 1)).collect(Collectors.toList());
        List<EsAttrBO> esAttrBOList = new ArrayList<>();
        for (SpuAttrValueVO attr : attrs) {
            EsAttrBO esAttrBO = new EsAttrBO();
            esAttrBO.setAttrId(attr.getAttrId());
            esAttrBO.setAttrValueId(attr.getAttrValueId());
            // 国际化信息
            Map<Integer, SpuAttrValueLangVO> spuAttrValueLangMap = attr.getSpuAttrValueLangList().stream()
                    .collect(Collectors.toMap(SpuAttrValueLangVO::getLang, s -> s));
            // 中文信息
            SpuAttrValueLangVO spuAttrValueZh = spuAttrValueLangMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang());
            esAttrBO.setAttrNameZh(spuAttrValueZh.getAttrName());
            esAttrBO.setAttrValueNameZh(spuAttrValueZh.getAttrValueName());
            // 英文信息
            SpuAttrValueLangVO spuAttrValueEn = spuAttrValueLangMap.get(LanguageEnum.LANGUAGE_EN.getLang());
            if (Objects.nonNull(spuAttrValueEn)) {
                esAttrBO.setAttrNameEn(spuAttrValueEn.getAttrName());
                esAttrBO.setAttrValueNameEn(spuAttrValueEn.getAttrValueName());
            }
            esAttrBOList.add(esAttrBO);
        }
        esProductBO.setAttrs(esAttrBOList);
    }

    /**
     * 处理分类数据
     *
     * @param category
     * @return
     */
    private EsCategoryBO handleCategory(CategoryVO category) {
        EsCategoryBO categoryBO = new EsCategoryBO();
        categoryBO.setCategoryId(category.getCategoryId());
        Map<Integer, String> categoryMap = category.getCategoryLangList().stream().collect(Collectors.toMap(CategoryLangVO::getLang, CategoryLangVO::getName));
        categoryBO.setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
        categoryBO.setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        return categoryBO;
    }

}
